import axios from 'axios';
import { UniAdapter } from 'uniapp-axios-adapter';
import { getToken, removeToken } from './auth';
import baseURL from './baseURL';
import store from '@/store'
let isLoading = false;
const request = axios.create({
	baseURL: baseURL,
	timeout: 5000,
	adapter: UniAdapter,
});
let reqCount = 0;
request.interceptors.request.use(config => {
	// 如果当前没有显示加载动画，则显示它
	// if (!isLoading && reqCount == 0) {
	// 	uni.showLoading({ title: '加载中...' });
	// 	isLoading = true;
	// }
	// 请求计数
	reqCount++;
	//带上token
	config.headers['token'] = getToken();
	return config;
});

request.interceptors.response.use(
	response => {
		if (isLoading) {
			// 隐藏加载动画
			// uni.hideLoading();
			isLoading = false;
		}
		// 统一处理响应,返回Promise以便链式调用
		if (response.status === 200) {
			reqCount--;
			const { data } = response;
			if (data && data.code === 200) {
				return Promise.resolve(data);
			} else if (reqCount === 0 && data && data.code === 401) {
				removeToken();
				store.dispatch('car/addToCar', { total: 0, size: 0 });
				uni.removeStorageSync('customerPhone');
				uni.utils.toast('请先登录', 'none', true);
				let timer = setTimeout(() => {
					clearTimeout(timer);
					timer = null;
					uni.navigateTo({ url: '/pages/login/login' });
				}, 300);
				return Promise.reject(data);
			} else {
				uni.utils.toast(data.message);
				return Promise.reject(data);
			}
		}
	},
	error => {
		// 请求失败时也隐藏加载动画
		// if (isLoading) {
		// 	// 隐藏加载动画
		// 	// uni.hideLoading();
		// 	isLoading = false;
		// }
		if (error.errMsg.includes('timeout') || error.errMsg === 'Network Error') {
			uni.utils.toast("网络超时");
			return Promise.reject(error)
		} else {
			uni.utils.toast("网络超时");
			// uni.utils.toast("接口请求失败");
			return Promise.reject(error)
		}
	}
);

export default request;